package com.xuecheng.learning.service.Impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.learning.config.PayNotifyConfig;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.service.MyCourseTablesService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ReceivePayNotifyServiceImpl {
    @Autowired
    MyCourseTablesService myCourseTablesService;
    @RabbitListener(queues = PayNotifyConfig.PAYNOTIFY_QUEUE)
    public void receive(Message message){
        try {
            //执行异常重新执行时，先休眠5秒
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //接收消息
        byte[] body = message.getBody();
        String jsonString = new String(body);
        MqMessage mqMessage = JSON.parseObject(jsonString, MqMessage.class);
        //获取消息类型
        String messageType = mqMessage.getMessageType();
        //获取选课id
        String chooseId = mqMessage.getBusinessKey1();
        //获取支付类型
        String orderType = mqMessage.getBusinessKey2();
        //该监听方法只监听支付结果的消息类型
        if (PayNotifyConfig.MESSAGE_TYPE.equals(messageType)){
            //该方法只执行有关课程购买的订单
            if ("60201".equals(orderType)){
                //保存选课记录修改支付结果为已支付
                boolean b = myCourseTablesService.saveChooseCourseStatus(chooseId);
                if (!b){
                    log.debug("接收该选课id的支付信息后，更改选课状态失败{}",chooseId);
                    XueChengPlusException.cast("接收该选课id的支付信息后，更改选课状态失败");
                }
            }
        }
    }
}
